package com.nuist.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.nuist.entity.Meter;
import com.nuist.result.Result;
import com.nuist.service.MeterService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author 梁科
 * @Version 1.0
 * @ Date 2025/10/16 23:47
 */
@RequestMapping(value = "/meter")
@Slf4j
@RestController
@Api(tags = "电表相关接口")
public class MeterController {
    @Resource
    private MeterService meterService;

    /**
     * 返回电表信息(加入/查询redis缓存数据 key = Meter)
     *
     * @return
     */
    @ApiOperation(value = "返回电表信息")
    @GetMapping(value = "/list")
    public Result<List<Meter>> selectAll() {
        List<Meter> meters = meterService.list();
        return Result.success(meters);
    }

    /**
     * 返回电表最新的一条信息(加入/查询redis缓存数据 key = Meter)
     *
     * @return
     */
    @ApiOperation(value = "返回电表最新的一条信息")
    @GetMapping(value = "/latest")
    @Cacheable(cacheNames = "Meter",key = "'latestMeter'")
    public Result<Meter> meterLatest() {
        LambdaQueryWrapper<Meter> meterLambdaQueryWrapper = Wrappers.lambdaQuery(Meter.class);
        // 设置查询条件
        meterLambdaQueryWrapper.orderByDesc(Meter::getId).last("LIMIT 1");
        Meter meter = meterService.getOne(meterLambdaQueryWrapper);
        return Result.success(meter);
    }

    /**
     * 保存电表信息(删除redis缓存数据 key = Meter)
     *
     * @param meter
     * @return
     */
    @ApiOperation(value = "保存电表信息")
    @PostMapping(value = "/save")
    @CacheEvict(cacheNames = "Meter",allEntries = true)
    public Result saveMeter(@RequestBody Meter meter) {
        meterService.save(meter);
        return Result.success();
    }
}
